import axios from 'axios'

const state = {
  logs: []
}

const mutations = {
  SET_LOGS(state, logs) {
    state.logs = logs
  },
  ADD_LOG(state, log) {
    state.logs.unshift(log)
  }
}

const actions = {
  async fetchLogs({ commit }) {
    try {
      const response = await axios.get('/api/logs')
      commit('SET_LOGS', response.data)
      return response.data
    } catch (error) {
      throw error
    }
  },
  
  async fetchLogsByUsername({ commit }, username) {
    try {
      const response = await axios.get(`/api/logs/user/${username}`)
      commit('SET_LOGS', response.data)
      return response.data
    } catch (error) {
      throw error
    }
  },
  
  async fetchLogsByOperationType({ commit }, operationType) {
    try {
      const response = await axios.get(`/api/logs/operation/${operationType}`)
      commit('SET_LOGS', response.data)
      return response.data
    } catch (error) {
      throw error
    }
  },
  
  async fetchLogsByTimeRange({ commit }, { start, end }) {
    try {
      const response = await axios.get(`/api/logs/time-range?start=${start}&end=${end}`)
      commit('SET_LOGS', response.data)
      return response.data
    } catch (error) {
      throw error
    }
  },
  
  async fetchLogsByUsernameAndTimeRange({ commit }, { username, start, end }) {
    try {
      const response = await axios.get(`/api/logs/user/${username}/time-range?start=${start}&end=${end}`)
      commit('SET_LOGS', response.data)
      return response.data
    } catch (error) {
      throw error
    }
  }
}

const getters = {
  allLogs: state => state.logs
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}